package top.hjcwzx.wrench.mqtt.service.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import top.hjcwzx.wrench.mqtt.config.MqttConfigProperties;
import top.hjcwzx.wrench.mqtt.event.MqttConnectionLostEvent;
import top.hjcwzx.wrench.mqtt.service.core.MqttService;

/**
 *
 * <p><b>类名：</b> MqttConnectionLostHandler</p>
 * <p><b>描述：</b> mqtt断连重试</p>
 * <p><b>创建时间：</b> 2025-06-17 15:34</p>
 *
 * @author 胡锦程
 */
public class MqttConnectionLostHandler {

    private Logger log = LoggerFactory.getLogger(MqttConnectionLostHandler.class);
    private final MqttService mqttService;
    private final MqttConfigProperties configProperties;

    public MqttConnectionLostHandler(MqttService mqttService, MqttConfigProperties configProperties) {
        this.mqttService = mqttService;
        this.configProperties = configProperties;
    }

    @EventListener
    public void handleConnectionLost(MqttConnectionLostEvent event) {
        if (configProperties.getAutoReconnect()) {
            log.warn("⚠️ 检测到MQTT连接断开，开始尝试重连...");
            int retry = 0;
            while (retry <= 3) {
                retry++;
                log.info("🔄 第 " + retry + " 次尝试重连 MQTT...");
                if (mqttService.reconnect()) {
                    log.info("✅ MQTT 重连成功！");
                    return;
                } else {
                    log.error("❌ 第 " + retry + " 次重连失败");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ignored) {
                    }
                }
            }
        }
    }
}
